from django.shortcuts import render
# 导入student类
from student.models import Student
# 引入JsonResponse
from django.http import JsonResponse
# 导入uuid
import uuid
# 导入hashlib
import hashlib
# 导入settings
from django.conf import settings
# 导入os
import os
# 引入Excel读取类
from utils.exceloperator import ExcelReader


# Create your views here.

def index(request):
    """展示首页"""
    # 携带数据渲染页面
    return render(request, 'index.html')


def get_all_student(request):
    """获取后台所有学生的数据"""
    # 获取学生信息--[{},{},{},]
    obj_students = list(Student.objects.all().values())
    # 返回Json格式
    return JsonResponse({'result': obj_students}, json_dumps_params={'ensure_ascii': False})


def get_random_str():
    """生成随机的名称"""
    # 获取uuid的随机数
    uuid_val = uuid.uuid4()
    # 获取uuid的随机数字符串
    uuid_str = str(uuid_val).encode('utf-8')
    # 获取md5实例
    md5 = hashlib.md5()
    # 拿取uuid的md5摘要
    md5.update(uuid_str)
    # 返回固定长度的字符串
    return md5.hexdigest()


def upload(request):
    """接收上传的文件"""
    # ============1. 接收文件 ============
    # 接收上传的文件
    rev_file = request.FILES.get('excel_file')
    # 判断，是否有文件
    if not rev_file:
        return JsonResponse({'code': 0, 'msg': '文件不存在！'})
    # 获得一个唯一的名字： uuid +hash
    new_name = get_random_str()
    # 准备写入的URL
    file_path = os.path.join(settings.MEDIA_ROOT, new_name + os.path.splitext(rev_file.name)[1])
    # 开始写入到本次磁盘
    try:
        f = open(file_path, 'wb')
        # 多次写入
        for i in rev_file.chunks():
            f.write(i)
        # 要关闭
        f.close()

    except Exception as e:
        return JsonResponse({'code': 0, 'msg': str(e)})

    # ===============2. 读取Excel文件 =================
    infos = ['sno', 'name', 'gender', 'birthday', 'mobile', 'email', 'address']
    excel_reader_obj = ExcelReader(file_path, 'student', infos, True)

    # ===============3. 写入MySQL数据库 ================
    for student in excel_reader_obj.student02:
        # 实例化
        obj_student = Student(sno=student['sno'], name=student['name'], gender=student['gender'],
                              birthday=student['birthday'], mobile=student['mobile'], email=student['email'],
                              address=student['address'])
        # 保存
        obj_student.save()

    # ==============4. 重新读取数据库所有信息，显示在页面 ===========
    obj_students = list(Student.objects.all().values())
    # 返回Json格式
    return JsonResponse({'result': obj_students}, json_dumps_params={'ensure_ascii': False})